package com.arsl.client.presenter;

import java.sql.Date;

import com.arsl.client.GlobalInfo;
import com.arsl.client.PaperaziServiceAsync;
import com.arsl.client.data.Paper;
import com.arsl.client.event.ShowViewEvent;
import com.arsl.client.view.CreateARPageView;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;

public class CreateArPagePresenter implements Presenter {

	private PaperaziServiceAsync rpcService;
	private HandlerManager eventBus;
	private CreateARPageView view;
	private int createdArPageId;
	private int currentPaperId;

	public CreateArPagePresenter(PaperaziServiceAsync rpcService,
			HandlerManager eventBus, CreateARPageView createARPageView) {
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.view = createARPageView;
		view.setPresenter(this);
	}

	@Override
	public void go(HasWidgets container) {
		container.clear();
		container.add(view);
		loadPapers();
	}

	private void loadPapers() {
		view.populatePapers();
	}

	public void createARPage(final int paperId, final Date dt,
			final int editionId, final int sectionId, final int pageNo) {
		currentPaperId = paperId;
		rpcService.addPublication(paperId, dt, editionId,
				new AsyncCallback<Integer>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(Integer publicationId) {
						rpcService.addARPage(publicationId, sectionId, pageNo,
								new AsyncCallback<Integer>() {

									@Override
									public void onFailure(Throwable caught) {
										// TODO Auto-generated method
										// stub

									}

									@Override
									public void onSuccess(Integer arPageId) {
										createdArPageId = arPageId;
										view.setImage("/paperazi/httpservices?service=getQRCode&arPageId="
												+ arPageId);

									}
								});
					}
				});
	}

	public void goToTagging() {

		ShowViewEvent event = new ShowViewEvent();
		event.setArg(ShowViewEvent.VIEW_ARG, ShowViewEvent.VIEW_PAGE_TAGGER);
		event.setArg(ShowViewEvent.ARG_ARPAGEID, createdArPageId + "");
		event.setArg(ShowViewEvent.ARG_PAPERID, currentPaperId + "");
		eventBus.fireEvent(event);

	}
}
